// LoginFrame.java - 在合适位置添加默认信息提示
// LoginFrame.java - 修复注册按钮行为
package com.library.gui;

import com.library.entity.*;
import com.library.service.AuthService;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class LoginFrame extends JFrame {
    private AuthService authService;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private JComboBox<String> userTypeCombo;
    private JButton showDefaultInfoButton;
    
    // 添加当前用户类型状态
    private String currentUserType = "读者";

    public LoginFrame() {
        authService = new AuthService();
        initializeUI();
    }

    private void initializeUI() {
        setTitle("图书借阅管理系统 - 登录");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);
        setResizable(false);

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        mainPanel.setBackground(Color.WHITE);

        // 标题
        JLabel titleLabel = new JLabel("图书借阅管理系统", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(0, 102, 204));
        mainPanel.add(titleLabel, BorderLayout.NORTH);

        // 登录表单面板
        JPanel formPanel = new JPanel(new GridLayout(4, 2, 10, 15));
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        formPanel.setBackground(Color.WHITE);

        // 用户类型选择
        formPanel.add(new JLabel("用户类型:"));
        userTypeCombo = new JComboBox<>(new String[]{"读者", "管理员"});
        formPanel.add(userTypeCombo);

        // 用户名
        formPanel.add(new JLabel("用户名:"));
        usernameField = new JTextField();
        formPanel.add(usernameField);

        // 密码
        formPanel.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        formPanel.add(passwordField);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        buttonPanel.setBackground(Color.WHITE);

        // 第一行：登录注册按钮
        JPanel mainButtonPanel = new JPanel(new GridLayout(1, 2, 10, 0));
        mainButtonPanel.setBackground(Color.WHITE);

        loginButton = new JButton("登录");
        loginButton.setBackground(new Color(0, 102, 204));
        loginButton.setForeground(Color.black);
        loginButton.setFont(new Font("微软雅黑", Font.BOLD, 14));

        registerButton = new JButton("注册读者账户");
        registerButton.setBackground(new Color(76, 175, 80));
        registerButton.setForeground(Color.black);
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 14));

        mainButtonPanel.add(loginButton);
        mainButtonPanel.add(registerButton);

        // 第二行：默认信息按钮
        showDefaultInfoButton = new JButton("查看默认管理员账户");
        showDefaultInfoButton.setBackground(new Color(255, 152, 0));
        showDefaultInfoButton.setForeground(Color.black);
        showDefaultInfoButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));

        buttonPanel.add(mainButtonPanel);
        buttonPanel.add(showDefaultInfoButton);

        // 添加事件监听器
        loginButton.addActionListener(new LoginAction());
        registerButton.addActionListener(new RegisterAction());
        showDefaultInfoButton.addActionListener(new ShowDefaultInfoAction());
        
        // 添加用户类型切换监听器
        userTypeCombo.addItemListener(new UserTypeChangeListener());

        // 将表单和按钮添加到主面板
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(formPanel, BorderLayout.CENTER);
        centerPanel.add(buttonPanel, BorderLayout.SOUTH);
        centerPanel.setBackground(Color.WHITE);

        mainPanel.add(centerPanel, BorderLayout.CENTER);

        // 底部信息
        JLabel infoLabel = new JLabel("首次使用请先注册相应类型账户", JLabel.CENTER);
        infoLabel.setForeground(Color.GRAY);
        mainPanel.add(infoLabel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    // 用户类型切换监听器 - 修复版本
    private class UserTypeChangeListener implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                String selectedType = (String) userTypeCombo.getSelectedItem();
                currentUserType = selectedType; // 更新当前用户类型
                
                if ("管理员".equals(selectedType)) {
                    registerButton.setText("注册管理员账户");
                    registerButton.setBackground(new Color(156, 39, 176)); // 紫色
                    showDefaultInfoButton.setVisible(true);
                } else {
                    registerButton.setText("注册读者账户");
                    registerButton.setBackground(new Color(76, 175, 80)); // 绿色
                    showDefaultInfoButton.setVisible(false);
                }
            }
        }
    }

    private class LoginAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword());
            String userType = (String) userTypeCombo.getSelectedItem();

            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(LoginFrame.this, 
                    "请输入用户名和密码!", "输入错误", JOptionPane.WARNING_MESSAGE);
                return;
            }

            // 验证登录
            if (authService.login(username, password)) {
                User user = authService.getCurrentUser();
                
                // 验证用户类型
                if ((userType.equals("读者") && user.getRole() != User.UserRole.READER) ||
                    (userType.equals("管理员") && user.getRole() != User.UserRole.ADMIN)) {
                    JOptionPane.showMessageDialog(LoginFrame.this, 
                        "用户类型不匹配!", "登录失败", JOptionPane.ERROR_MESSAGE);
                    authService.logout();
                    return;
                }

                // 登录成功，跳转到相应页面
                LoginFrame.this.dispose();
                
                if (user.getRole() == User.UserRole.ADMIN) {
                    // 跳转到管理员页面
                    SwingUtilities.invokeLater(() -> {
                        LibraryManagementGUI adminGUI = new LibraryManagementGUI((Admin) user);
                        adminGUI.setVisible(true);
                        
                        // 显示欢迎信息
                        Admin admin = (Admin) user;
                        JOptionPane.showMessageDialog(adminGUI, 
                            "欢迎回来，" + admin.getRealName() + "！\n" +
                            "您已成功登录图书借阅管理系统管理员端。", 
                            "登录成功", JOptionPane.INFORMATION_MESSAGE);
                    });
                } else {
                    // 跳转到读者页面
                    SwingUtilities.invokeLater(() -> {
                        ReaderDashboard readerGUI = new ReaderDashboard((ReaderUser) user);
                        readerGUI.setVisible(true);
                    });
                }
                
            } else {
                JOptionPane.showMessageDialog(LoginFrame.this, 
                    "用户名或密码错误!", "登录失败", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private class RegisterAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 使用当前用户类型，而不是从下拉框重新获取
            if ("管理员".equals(currentUserType)) {
                // 打开管理员注册对话框
                System.out.println("打开管理员注册对话框"); // 调试信息
                new AdminRegisterDialog(LoginFrame.this, authService).setVisible(true);
            } else {
                // 打开读者注册对话框
                System.out.println("打开读者注册对话框"); // 调试信息
                new ReaderRegisterDialog(LoginFrame.this, authService).setVisible(true);
            }
        }
    }

    private class ShowDefaultInfoAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 显示默认管理员账户信息
            String message = "<html><body>" +
                "<h3>默认管理员账户信息</h3>" +
                "<table border='0' cellspacing='5'>" +
                "<tr><td><b>管理员姓名:</b></td><td>杨博锐</td></tr>" +
                "<tr><td><b>用户名:</b></td><td>admin</td></tr>" +
                "<tr><td><b>密码:</b></td><td>2083658769Ybr</td></tr>" +
                "<tr><td><b>用户类型:</b></td><td>管理员</td></tr>" +
                "</table>" +
                "<br><font color='red'>注意：请妥善保管管理员密码！</font>" +
                "</body></html>";
            
            JOptionPane.showMessageDialog(LoginFrame.this, message, 
                "默认管理员账户", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            LoginFrame loginFrame = new LoginFrame();
            loginFrame.setVisible(true);
        });
    }
}